package common

import "strconv"

type Pag struct {
	Num       int         `json:"page_num"`
	Size      int         `json:"page_size"`
	PageCount int         `json:"page_count"`
	ItemCount int         `json:"item_count"`
	Data      interface{} `json:"data"`
}

var DefaultPageNum = 1
var DefaultPageSize = 40

func (p *Pag) PageNum() int {
	if p.Num == 0 {
		return DefaultPageNum
	}
	return p.Num
}

func (p *Pag) PageSize() int {
	if p.Size == 0 {
		return DefaultPageSize
	}
	return p.Size
}

func (p *Pag) Limit() string {
	size := p.PageSize()
	offset := (p.PageNum() - 1) * size
	return "LIMIT " + strconv.Itoa(offset) + ", " + strconv.Itoa(size)
}

func (p *Pag) SetCount(count int) {
	if p.Num == 0 {
		p.Num = DefaultPageNum
	}
	if p.Size == 0 {
		p.Size = DefaultPageSize
	}
	p.ItemCount = count
	p.PageCount = count / p.Size
	if count%p.Size > 0 {
		p.PageCount++
	}
}

func (p *Pag) Query(dest interface{}, fields string, set string, order string, args ...interface{}) error {
	if err := Sql.Select(dest, "SELECT "+fields+" FROM "+set+" "+order+" "+p.Limit(), args...); err != nil {
		return err
	}
	count := 0
	if err := Sql.Get(&count, "SELECT count(*) FROM "+set, args...); err != nil {
		return err
	}
	p.SetCount(count)
	p.Data = dest
	return nil
}
